﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using Ccit.Utils;
using System.Collections.Generic;
using System.Text;
using Newtonsoft.Json;
using Ccit.OA.Utils;

namespace Ccit.OA.NewsCenter
{
    public partial class news_page_browse : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                _hidType.Value = (null != Request.QueryString["Type"]) ? Request.QueryString["Type"].ToString() : "0";
                LoginUser login = (LoginUser)HttpContext.Current.Session["LogUserInfo"];
                if (login == null)
                    lblShowMes.Text = "<font color='red'  size='+1'>无效用户,请您重新登陆...</font>";
                else
                {
                    showLayOut(login);
                }
            }
        }

        #region 私有方法

        private void showLayOut(LoginUser login)
        {
            _hidUserId.Value = login.UserId;

            LayoutBLL bll = new LayoutBLL();

            MsLayout layOut = bll.GetLayOutObj(login.UserId, _hidType.Value);

            if(layOut == null)   //没有布局显示系统布局
                layOut = bll.GetLayOutDefault(_hidType.Value);
            if (layOut != null)   
            {
                // create display
                string cellCount = layOut.CellCount;
                _hidCellCount.Value = cellCount; //列数
                setTableFrame(cellCount, layOut);  // set frame style

                string cellIndex = "0";
                HtmlGenericControl htUl;
                for (int i = 0; i < Int32.Parse(cellCount); i++)
                {
                    cellIndex = (i + 1).ToString();
                    htUl = createCellLayOut(layOut, cellIndex);
                    switch (cellIndex)
                    {
                        case "1":
                            tdOneFrm.Controls.Add(htUl);
                            break;
                        case "2":
                            tdTwoFrm.Controls.Add(htUl);
                            break;
                        case "3":
                            tdThreeFrm.Controls.Add(htUl);
                            break;
                    }
                }
            }
        }

        /// <summary>
        /// by layout cellcount set table frame style  设置每列的宽
        /// </summary>
        /// <param name="cellCount"></param>
        /// <param name="msLayOut"></param>
        private void setTableFrame(string cellCount, MsLayout msLayOut)
        {
            string oneCellWidth = msLayOut.OneCellWidth;
            string twoCellWidth = msLayOut.TwoCellWidth;
            string threeCellWidth = msLayOut.ThreeCellWidth;

            switch (cellCount)  //判断列数，设定列的宽度
            {
                case "1":
                    tdThreeFrm.Style["display"] = "none";
                    tdTwoFrm.Style["display"] = "none";
                    tdOneFrm.Style["width"] = "98%";
                    break;
                case "2":
                    tdThreeFrm.Style["display"] = "none";
                    tdTwoFrm.Style["width"] = (Int32.Parse(twoCellWidth) - 2).ToString() + "%";
                    tdOneFrm.Style["width"] = (Int32.Parse(oneCellWidth) - 2).ToString() + "%";
                    break;
                case "3":
                    tdThreeFrm.Style["width"] = (Int32.Parse(threeCellWidth) - 2).ToString() + "%";
                    tdTwoFrm.Style["width"] = (Int32.Parse(twoCellWidth) - 2).ToString() + "%";
                    tdOneFrm.Style["width"] = (Int32.Parse(oneCellWidth) - 2).ToString() + "%";
                    break;
            }
        }

        private HtmlGenericControl createCellLayOut(MsLayout msLayOut, string cellIndex)
        {
            HtmlGenericControl htUl = new HtmlGenericControl("ul");
            string ctrlId_UL = "sort_" + cellIndex;   // ul control id
            htUl.ID = ctrlId_UL;
            htUl.Style.Add("list-style-type", "none");
            htUl.Style.Add("margin", "0");
            htUl.Style.Add("padding", "0");

            WindowBLL bll = new WindowBLL();

            List<MsWinStyle> lstPlate = new List<MsWinStyle>();

            if (msLayOut.UserId == "-999")  //新用户显示的板块为系统板块
            {
                switch (cellIndex)
                {
                    case "1":
                        lstPlate = bll.GetDefaultWin("1", _hidType.Value);
                        break;
                    case "2":
                        lstPlate = bll.GetDefaultWin("2", _hidType.Value);
                        break;
                    case "3":
                        lstPlate = bll.GetDefaultWin("3", _hidType.Value);
                        break;
                }
            }
            else    
            {
                switch (cellIndex)
                {
                    case "1":
                        lstPlate = bll.GetWinShowCell("1", _hidType.Value);
                        break;
                    case "2":
                        lstPlate = bll.GetWinShowCell("2", _hidType.Value);
                        break;
                    case "3":
                        lstPlate = bll.GetWinShowCell("3", _hidType.Value);
                        break;
                }
            }

            if (null == lstPlate || lstPlate.Count == 0) return htUl;

            int icount = lstPlate.Count;
            bool bHas = findImagePlate(lstPlate);
            HtmlGenericControl htLi;
            MsWinStyle msPlate;
            for (int i = 0; i < icount; i++)
            {
                htLi = new HtmlGenericControl("li");
                msPlate = lstPlate[i];
                htLi.ID = ctrlId_UL + "_" + msPlate.PlateId;
                htLi.Attributes["class"] = "moveCell";
                htLi.InnerHtml = createPlateTable(msPlate, icount, bHas,msLayOut);

                htUl.Controls.Add(htLi);
            }

            return htUl;
        }

        //查询板块是否存在image板块
        private bool findImagePlate(List<MsWinStyle> lstPlate)
        {
            bool bHas = false;
            if (null == lstPlate || lstPlate.Count == 0) return bHas;

            try
            {
                MsWinStyle msPlate = lstPlate.Single(p => p.PlateId == "-1");

                if (null != msPlate)
                    bHas = true;
            }
            catch { bHas = false; }
            return bHas;
        }


        //创建板块
        private string createPlateTable(MsWinStyle msPlate, int colPlateCount, bool bHasImage,MsLayout msLayout)
        {
            _hidSysPlateId.Value = msLayout.UserId;
            StringBuilder sb = new StringBuilder();

            string tblHeight = setPlateTableHeight(colPlateCount, bHasImage);

            if (msPlate.SysFlag == "0")  //普通板块
                sb.Append("<table width='99%' height='").Append(tblHeight).Append("' border='0' align='center' cellpadding='0' cellspacing='0'>");
            else     //系统板块
            {
                if (msPlate.PlateId == "-1")
                    sb.Append("<table width='99%' height='245' border='0' align='center' cellpadding='0' cellspacing='0'>");
            }

            sb.Append("<tr><td class='fonts'>");
            sb.Append("<table width='100%'  border='0' cellspacing='0' cellpadding='0'>");

            if (msPlate.TitleStyle != "")
                sb.Append("<tr bgcolor='#").Append(msPlate.TitleStyle).Append("'>");
            else
                sb.Append("<tr bgcolor='#CDCECF'>");

            sb.Append("<td colspan='3'><img src='../images/str.gif' width='1' height='1'></td>");
            sb.Append("</tr><tr>");

            if (msPlate.TitleStyle != "")
                sb.Append("<td bgcolor='#").Append(msPlate.TitleStyle).Append("' width='1'>");
            else
                sb.Append("<td bgcolor='#CDCECF' width='1'>");

            sb.Append("<img src='../images/str.gif' width='1' height='1'></td>");


            sb.Append("<td height='22' background='../images/right_titlebg.gif'>");

            sb.Append("<table width='100%'  border='0' cellspacing='0' cellpadding='0'>");
            sb.Append("<tr><td><span class='fontbold'>&nbsp;");

            if (msPlate.PlateLogo == "")
                sb.Append("<img src='../images/icon/DOT.GIF' width='12' height='12' align='absmiddle'>");
            else
                sb.Append("<img src='" + msPlate.PlateLogo + "' width='18' height='18' align='absmiddle'>");
            sb.Append(msPlate.PlateName);
            sb.Append("</span></td>");
            sb.Append("<td>");
            sb.Append("<table width='60'  border='0' align='right' cellpadding='0' cellspacing='0'>");
            sb.Append("<tr>");
            sb.Append("<td><div align='center'></div></td>");  // add plate toolbar operation buttion
            sb.Append("<td><div align='center'></div></td>");  // add plate toolbar operation buttion
            sb.Append("<td><div align='center'></div></td>");  // add plate toolbar operation buttion
            sb.Append("<td><div align='right'><a style='cursor:hand;' onclick='javascript:doSetWinAttr(" + msPlate.PlateId + ","+msLayout.UserId+");'><img src='../images/edit_logo/EVENTS.GIF' height='25' width='25' /></a></div></td>");  // add plate toolbar operation buttion
            sb.Append("</tr></table></td></tr></table></td>");

            if (msPlate.TitleStyle != "")
                sb.Append("<td bgcolor='#").Append(msPlate.TitleStyle).Append("' width='1'>");
            else
                sb.Append("<td bgcolor='#CDCECF' width='1'>");


            sb.Append("<img src='../images/str.gif' width='1' height='1'></td>");

            if (msPlate.TitleStyle != "")
                sb.Append("</tr><tr bgcolor='#").Append(msPlate.TitleStyle).Append("'>");
            else
                sb.Append("</tr><tr bgcolor='#CDCECF'>");


            sb.Append("<td colspan='3'><img src='../images/str.gif' width='1' height='1'></td>");
            sb.Append("</tr></table></td></tr>");
            sb.Append("<tr>");
            sb.Append("<td valign='top' style='height:98%' class='fonts'>");
            //显示数据
            sb.Append("<table  width='100%' style='height:100%' border='0' cellspacing='0' cellpadding='0'>");
            sb.Append("<tr>");

            if (msPlate.TitleStyle != "")
                sb.Append("<td bgcolor='#").Append(msPlate.TitleStyle).Append("' width='1'>");
            else
                sb.Append("<td bgcolor='#CDCECF' width='1'>");

            sb.Append("<img src='../images/str.gif' width='1' height='1'></td>");
            sb.Append("<td style='height:100%' valign='top' >");
            sb.Append("<div align='center' id='div_").Append(msPlate.PlateId).Append("'>");

            if (msPlate.SysFlag == "0")
                sb.Append(getPlateDataItem(msPlate));   //  普通板块
            else
            {
                if (msPlate.PlateId == "-1")
                    sb.Append(getImgPlateItem(msPlate));   //图片板块
            }


            sb.Append("</div></td>");

            if (msPlate.TitleStyle != "")
                sb.Append("<td bgcolor='#").Append(msPlate.TitleStyle).Append("' width='1'>");
            else
                sb.Append("<td bgcolor='#CDCECF' width='1'>");

            sb.Append("<img src='../images/str.gif' width='1' height='1'></td>");
            sb.Append("</tr>");

            if (msPlate.TitleStyle != "")
                sb.Append("<tr bgcolor='#").Append(msPlate.TitleStyle).Append("'>");
            else
                sb.Append("<tr bgcolor='#CDCECF'>");

            sb.Append("<td colspan='3'><img src='../images/str.gif' width='1' height='1'></td>");
            sb.Append("</tr></table></td></tr><tr><td><img src='../images/str.gif' width='1' height='4'></td></tr></table>");


            return sb.ToString();
        }

        private string setPlateTableHeight(int colPlateCount, bool isHasImage)
        {
            string heightValue = "100%";
            if (colPlateCount == 0) return heightValue;

            double dAll = (isHasImage) ? Int32.Parse(_hid1.Value) : 100;
            double dHeight = dAll / colPlateCount;
            double dAdjParam = Int32.Parse(_hid2.Value);
            heightValue = (dHeight - dAdjParam).ToString() + "%";
            //heightValue = "240px";
            return heightValue;
        }

        //设置图片板块的高
        private string setImageSize()
        {
            string oneCell = tdOneFrm.Style["width"];
            string twoCell = tdTwoFrm.Style["width"];
            string threeCell = tdThreeFrm.Style["width"];
            int OnecellWidth = 0;
            int TwoCellWidth = 0;
            int ThreeCellWidth = 0;
            if (oneCell != "" && oneCell != null)
            {
                OnecellWidth = int.Parse(oneCell.Substring(0, tdOneFrm.Style["width"].Length - 1));
            }
            if (twoCell != "" && twoCell != null)
            {
                TwoCellWidth = int.Parse(twoCell.Substring(0, tdTwoFrm.Style["width"].Length - 1));
            }
            if (threeCell != "" && threeCell != null)
            {
                ThreeCellWidth = int.Parse(threeCell.Substring(0, tdThreeFrm.Style["width"].Length - 1));
            }
            string ImageHeight = "";
            string ImageWidth = "";
            if (OnecellWidth > 30 || TwoCellWidth > 30 || ThreeCellWidth > 30)
            {
                ImageHeight = "70%";
                ImageWidth = "80%";
            }
            else
            {
                ImageHeight = "90%";
                ImageWidth = "210px";
            }
            return ImageWidth + "~" + ImageHeight;
        }

        //图片板块  显示图片
        private string getImgPlateItem(MsWinStyle msPlate)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("<style type='text/css'>img{border:0;}#index_page{float:right;display:block;height:16px;padding:2px 0;margin-right:4px;}#index_page *{float:left;display:inline;line-height:16px;border:1px solid #B6CFCD;text-align:center;padding:0;margin:0 2px;}#index_page strong{background:#009A91;color:#fff;width:16px;}#index_page a{width:16px;color:#009A91;text-decoration:none;}</style>");
            sb.Append("<div id='tbl_data_").Append(msPlate.PlateId).Append("'>");

            LayoutBLL bll = new LayoutBLL();
            SubmitBLL subBll = new SubmitBLL();

            List<MsNews> newsList = bll.GetPubNews(_hidType.Value);

            #region  显示的条数
            int count = 0;
            if (msPlate.ShowNum != "" && msPlate.ShowNum != "0")
            {
                count = Convert.ToInt32(msPlate.ShowNum);
                if (newsList.Count > count)
                    count = count;
                else
                    count = newsList.Count;
            }
            if (msPlate.ShowNum == "0")
                count = newsList.Count;


            #endregion

            if (count == 0) //空数据 
            {
                sb.Append("<table><tr><td height='10' valign='top'><img width='9' height='10'><a href='#'>&nbsp;</a></td></tr><tr><td height='1' valign='top'><img width='6' height='1'></td></tr></table>");
                sb.Append("<table><tr><td height='10' valign='top'><img width='9' height='10'><a href='#'>&nbsp;</a></td></tr><tr><td height='1' valign='top'><img width='6' height='1'></td></tr></table>");
            }
            else    //存在数据
            {
                sb.Append("<script language='javascript' type='text/javascript'>var _t1 = 0;var _t2 = 5;var _tnum =").Append(count).Append(";var _tn = 1;var _tl =null; _tt1 = setTimeout('change_img()',_t1*1000);function change_img(){setFocus(_tn); _tt1 = setTimeout('change_img()',_t2*1000); }function setFocus(i){if(i>_tnum){_tn=1;i=1;}_tl?document.getElementById('focusPic'+_tl).style.display='none':'';document.getElementById('focusPic'+i).style.display='block'; _tl=i;_tn++;}</script>");
                //图片自动适应层大小
                string ImageSize = setImageSize();    //获取显示图片的大小
                string[] arrayImage = ImageSize.Split('~');
                string ImageWidth = arrayImage[0];
                string ImageHeight = arrayImage[1];

                sb.Append("<style type='text/css'>");
                sb.Append("#pic{ align:center; width:98%; height:88%; padding:0; border:0px solid #CDCECF; }");
             //   sb.Append("#pic img{max-width:").Append(ImageWidth).Append(";");
               // sb.Append(" height:").Append(ImageHeight).Append(";}");
                sb.Append("</style>");
                sb.Append("<div id='pic'>");
                for (int i = 0; i < count; i++)
                {
                    if (i == 0)
                        sb.Append("<div id='focusPic").Append(i + 1).Append("'>");
                    else
                        sb.Append("<div id='focusPic").Append(i + 1).Append("' style='display:none'>");

                    sb.Append("<div align='center' style='margin:2px;padding:2px;border:1px solid #CDCECF; '>");

                    MsImage msImg = subBll.GetImageByNewsId(newsList[i].NewsId, _hidType.Value);

                    string sPageParam = "tablename=NEWS_A5&keyfield=NEWS_A5_10&keyfieldvalue=" + msImg.PicId + "&imagefield=NEWS_A5_20";
                    string encodeParam = base64encode(sPageParam);
                    string picURL = "../UserControls/attach_image_show.aspx?" + encodeParam;   //图片路径                   

                    string sPageNewsIdParam = "Id=" + newsList[i].NewsId + "";
                    string encodeNewsIdParam = base64encode(sPageNewsIdParam);
                    sb.Append("<a href='news_inform_view.aspx?" + encodeNewsIdParam + "' target='_blank'>");

                    if (msImg.PicId == "" || msImg.PicId == null) //没有图片
                        sb.Append("<img id='00_imgnews' src='../images/no_picture.gif' alt='").Append(newsList[i].NewsTitle).Append("'/>");
                    else                           //存在图片
                        sb.Append("<img id='"+i.ToString()+"_imgnews'  src='").Append(picURL).Append("' alt='").Append(newsList[i].NewsTitle).Append("'/>");
                    
                    sb.Append("</a>");

                    sb.Append("</div>");
                    sb.Append("<div style='float:left;padding-top:2px;padding-left:14px '>").Append("<a href='news_inform_view.aspx?" + encodeNewsIdParam + "' target='_blank'>").Append(newsList[i].NewsTitle).Append("</a>").Append("</div>");
                    sb.Append("<div id='index_page'>");
                    for (int k = 0; k < count; k++)
                    {
                        //页码显示
                        if (i == k)
                            sb.Append("<a href='javascript:setFocus(" + (k + 1) + ");' style='color:red'>").Append(k + 1).Append("</a>");
                        else
                            sb.Append("<a href='javascript:setFocus(" + (k + 1) + ");' >").Append(k + 1).Append("</a>");
                    }
                    sb.Append("</div></div>");
                }
            }
            sb.Append("</div>");
            return sb.ToString();
        }


        private string base64encode(string sPageParam)
        {
            string encodeParam = string.Empty;
            if (string.IsNullOrEmpty(sPageParam)) return encodeParam;

            encodeParam = Base64Lib.Encode(sPageParam);
            return encodeParam;
        }

        //普通板块数据
        private string getPlateDataItem(MsWinStyle msPlate)
        {
            QueryBLL queryBll = new QueryBLL();

            MsQueryClause queryClause = queryBll.GetClauseObj(msPlate.PlateId);
            MsClauseAttr clauseAttr = new MsClauseAttr(queryClause.ClauseContent);
            clauseAttr.NewsStatus = "2";  //已发布

            SubmitBLL subBll = new SubmitBLL();
            List<MsNews> newsList = subBll.GetNewsByClause(clauseAttr, "", _hidType.Value);

            StringBuilder sb = new StringBuilder();
            sb.Append("<table id='tbl_data_").Append(msPlate.PlateId).Append("' width='95%' height='99%' border='0' align='center' valign='top' cellpadding='0' cellspacing='0'>");
            sb.Append("<tr><td valign='top'><table width='100%'>");

            #region  显示的条数
            int count = 0;
            if (msPlate.ShowNum != "" && msPlate.ShowNum != "0")
            {
                count = Convert.ToInt32(msPlate.ShowNum);
                if (newsList.Count > count)
                    count = count;
                else
                    count = newsList.Count;
            }
            if (msPlate.ShowNum == "0")
                count = newsList.Count;

            #endregion

            if (count == 0) //空数据 
            {
                sb.Append("<tr><td height='10' valign='top'><img width='9' height='10'><a href='#'>&nbsp;</a></td></tr><tr><td height='1' valign='top'><img width='6' height='1'></td></tr>");
                sb.Append("</table>");
                sb.Append("<table><tr><td height='10' valign='top'><img width='9' height='10'><a href='#'>&nbsp;</a></td></tr><tr><td height='1' valign='top'><img width='6' height='1'></td></tr>");
            }
            else    //存在数据
            {
                for (int i = 0; i < count; i++)
                {
                    string sPageNewsIdParam = "Id=" + newsList[i].NewsId + "";
                    string encodeNewsIdParam = base64encode(sPageNewsIdParam);
                    sb.Append("<tr align='left'><td>  ").Append("<a href='news_inform_view.aspx?" + encodeNewsIdParam + "'  target='_blank'>").Append(newsList[i].NewsTitle);
                    WindowBLL winBll = new WindowBLL();
                    if (msPlate.ShowPubTime == "1") //显示创建日期
                    {
                        string pubDate = winBll.GetPubDate(newsList[i].NewsId);
                        sb.Append("&nbsp;&nbsp;(").Append(pubDate).Append(")");
                    }
                    if (msPlate.ShowCreateor == "1") //显示创建人
                    {
                        string userName = SysInterface.GetNameStrByIdStr("SYS_A1", "SYS_A1_10", "SYS_A1_40", winBll.GetUserId(newsList[i].NewsId), "");
                        sb.Append("&nbsp;&nbsp;[").Append(userName).Append("]");
                    }
                    sb.Append("</td></tr>");
                }
            }

            sb.Append("</table>");

            sb.Append("</td></tr></table>");

            return sb.ToString();
        }
        #endregion

        #region   Ajax方法

        //获取板块对象
        [global::System.Web.Services.WebMethod]
        public static string GetPlateObj(string vplateId, string Type,string vUserId)
        {
            WindowBLL bll = new WindowBLL();
            MsWinStyle winObj = null;
            if (vUserId == "-999")
            {
                winObj = bll.GetWinStyleObj(vplateId, Type);
                if(winObj == null)
                    winObj = bll.GetWinDefault(vplateId, Type, vUserId);
            }
            else
            {
                winObj = bll.GetWinStyleObj(vplateId, Type);
            }
            var oResult = new { plateId = vplateId, plateName = winObj.PlateName, titleStyle = winObj.TitleStyle, showNo = winObj.ShowNum, showDate = winObj.ShowPubTime, showCreator = winObj.ShowCreateor };
            string str = "GetPlateObj" + "~" + JavaScriptConvert.SerializeObject(oResult) + "~" + winObj.PlateLogo;
            return str;
        }

        //编辑板块
        [global::System.Web.Services.WebMethod]
        public static string EditPlate(string jsonExpr, string Type,string vUserId)
        {
            MsWinStyle winObj = (MsWinStyle)JavaScriptConvert.DeserializeObject(jsonExpr, typeof(MsWinStyle));
            WindowBLL bll = new WindowBLL();
            List<string> strlist = bll.ModifyWinStyleObj(winObj, Type,vUserId);
            var oResult = new { resFlag = strlist[0], resMes = strlist[1] };
            return "EditPlate" + "~" + JavaScriptConvert.SerializeObject(oResult);
        }
        #endregion
    }
}
